from pathlib import Path
import os
from requests import get
import zipfile
import subprocess
import sys

# port = int(sys.argv[1])
# agent_port = int(sys.argv[2])
# port = 10001

target_ports = []
n = len(sys.argv)
for i in range(1, n):
    target_ports.append(int(sys.argv[i]))

def init():
    p_str = "C:\\users\\netease\\frp"
    path = Path(p_str)
    path.mkdir(parents=True, exist_ok=True)

    # Get the current working directory
    cwd = os.getcwd()

    # Print the current working directory
    print("Current working directory: {0}".format(cwd))

    # Change the current working directory
    os.chdir(p_str)

    # Print the current working directory
    print("Current working directory: {0}".format(os.getcwd()))

    frp_file_url = "https://gitlab.com/wsszh/file-server/-/raw/main/frp_0.38.0_windows_test.zip?inline=false"
    frp_path = "frp_0.38.0_windows_test"
    frp_file = frp_path + ".zip"

    # download frp
    with open(frp_file, "wb") as file:
        resp = get(frp_file_url)
        file.write(resp.content)

    # unzip
    with zipfile.ZipFile(frp_file, "r") as zip_ref:
        zip_ref.extractall(".")

    os.chdir(frp_path)

    in_file = r'frpc-cloudgame.ini'
    # replace_in_file(in_file, in_file, "[RDP]", "[RPD-{port}]".format(port=port))
    # replace_in_file(in_file, in_file, "RDP-PORT", str(port))
    # replace_in_file(in_file, in_file, "[http]", "[http-{agent_port}-{port}]".format(port=port, agent_port=agent_port))

    for i in range(len(target_ports)):
        replace_in_file(in_file, in_file, "TARGET-PORT{i}".format(i=i), str(target_ports[i]))

    subprocess.Popen(["frpc.exe", "-c", in_file])
    subprocess.Popen(["start", "powershell"], shell = True)

def replace_in_file(in_file, out_file, search_text, replace_text):
    # Opening our text file in read only
    # mode using the open() function
    with open(in_file, 'r') as file:

        # Reading the content of the file
        # using the read() function and storing
        # them in a new variable
        data = file.read()

        # Searching and replacing the text
        # using the replace() function
        data = data.replace(search_text, replace_text)

    # Opening our text file in write only
    # mode to write the replaced content
    with open(out_file, 'w') as file:

        # Writing the replaced data in our
        # text file
        file.write(data)


def init_cloudgame():
    os.system('C:\\Python38\\python.exe -m pip install flask flask_cors flask_executor pypiwin32 requests '
              'psutil prometheus-client gevent flask_sockets')
    os.system('E:\\startup\\VC_redist.x64.exe /quiet /noretstart')
    os.system('E:\\startup\\autoit-v3-setup.exe /S')
    os.chdir('E:\\startup\\PyAutoIt-0.4\\')
    os.system('C:\\Python38\\python.exe setup.py install')
    os.system('mkdir E:\\CloudGameLogs')
    os.system(
        'C:\\Python38\\python.exe E:\\startup\\CloudGameServer\\agent.py > E:\\CloudGameLogs\\instance.log 2>&1 &')


if __name__ == "__main__":
    init()
    init_cloudgame()
